"""
python fujian1_smooth.py
"""


import os
import json
import pandas as pd

# 输入和输出路径
input_dir = "fujian/fujian1/group_output"
output_dir = "fujian/fujian1/smooth_preprocess"
os.makedirs(output_dir, exist_ok=True)

# 移动平均和指数平滑设置
window_size = 2  # 移动平均窗口
alpha = 0.8      # 指数平滑因子

# 遍历每个 JSON 文件
for filename in os.listdir(input_dir):
    if filename.endswith(".json"):
        filepath = os.path.join(input_dir, filename)
        
        # 读取 JSON 数据
        with open(filepath, 'r', encoding='utf-8') as file:
            data = json.load(file)
        
        # 转换为 DataFrame
        df = pd.DataFrame(data)
        df['date'] = pd.to_datetime(df['date'])
        df.set_index('date', inplace=True)

        # 应用移动平均和指数平滑
        df['smoothed_inventory'] = df['inventory'].rolling(window=window_size, min_periods=1).mean()
        df['smoothed_inventory'] = df['smoothed_inventory'].ewm(alpha=alpha).mean()

        # 准备输出格式
        smoothed_data = [
            {"date": date.strftime('%Y-%m-%d'), "inventory": int(round(inv))}
            for date, inv in zip(df.index, df['smoothed_inventory'])
        ]

        # 保存到指定目录
        output_filepath = os.path.join(output_dir, filename)
        with open(output_filepath, 'w', encoding='utf-8') as output_file:
            json.dump(smoothed_data, output_file, ensure_ascii=False, indent=4)
        
        print(f"Processed and saved: {output_filepath}")
